package org.example.upload.controller;

import cn.hutool.core.io.file.FileNameUtil;
import org.example.vo.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

import static org.example.utils.MallConstant.FILE_SERVER_FOLDER;
import static org.example.utils.MallConstant.USER_IMG_FORMAT;

@RestController
@RequestMapping("/userFile")
public class FileUploadController {


    @GetMapping("/{userID}/{type}")
    /*
     * 从文件夹中获取用户照片，需要验证用户token的id与保存的id一致
     * 1 、营业执照 2、身份证照片
     */
    public String getUserFile(@PathVariable String type, @PathVariable String userID, HttpServletResponse response){
        File img=new File(FILE_SERVER_FOLDER+"/"+userID+"-"+type + USER_IMG_FORMAT);
        //如果文件不存在，返回404
        if (!img.exists()){
            response.setStatus(404);
            return "";
        }
        //发送文件
        try(FileInputStream inputStream=new FileInputStream(img)) {
            byte[] bytes = inputStream.readAllBytes();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return "";
        }

    }

    @PostMapping("/{userID}/{type}")
    /*
     * 批量保存用户照片将用户照片保存到服务器绝对路径中，不作静态资源映射以保证数据安全
     */
    public Result<?> uploadUserFile(@PathVariable String userID, @PathVariable String type, @RequestParam("file")MultipartFile img) {
        //获取文件名
        String imgName = img.getOriginalFilename();
        //获取扩展名
        String suffix = FileNameUtil.getSuffix(imgName);
        if (suffix==null || suffix.matches("/(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/")){
            return Result.failed("文件格式错误");
        }
        InputStream inputStream = null;
        byte[] bytes;
        try {
            //获取图片二进制数据
            bytes=img.getBytes();
            //转换为png格式
            inputStream = img.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.white, null);
            //保存文件并返回base64编码后的字符串
            ImageIO.write(newBufferedImage, "png", new File(FILE_SERVER_FOLDER+"/"+userID+"-"+type + USER_IMG_FORMAT));
        } catch (IOException e) {
            return Result.failed("文件格式错误");

        }
        //修改状态并

        return Result.success(Base64.getEncoder().encodeToString(bytes));
    }
}
